import { Anything } from 'utils/types/any';
import { hashGroup } from './list';

const _getMenu = <T extends Anything>(
  list: { [key: string]: T[] },
  pid: string,
) => {
  const sub_list: T[] = [];
  list[pid].forEach((item: T) => {
    // 重难点
    const tmp = item as unknown as {
      id: string;
      sub_list?: T[];
      has_child: number;
    };
    tmp.has_child = 0;
    if (list[tmp.id]) {
      tmp.sub_list = _getMenu(list, tmp.id);
      if (tmp.sub_list.length > 0) tmp.has_child = 1;
    }
    sub_list.push(item);
  });
  return sub_list;
};

export const getHomeMenu = (menuList: Anything[]) => {
  const hashList = hashGroup(menuList, 'parent_id');
  const list = _getMenu(hashList, '');
  return list;
};
